Scroll Progress Bar

Matrix Addition

Matrix addition involves adding two matrices of the same dimensions. For matrix addition to be valid, both matrices must have the same number of rows and columns. The addition of matrices is performed by adding the corresponding elements of each matrix and storing the result in a new matrix.

Usage and Approach:

In C, matrices are typically represented as two-dimensional arrays. To perform matrix addition, can use nested loops to iterate over each element of the matrices and add the corresponding elements.

Sample Code with Explanation and Output:

#include <stdio.h>

// Function to perform matrix addition
void matrixAddition(int rows, int columns, int matrix1[][3], int matrix2[][3], int result[][3]) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            result[i][j] = matrix1[i][j] + matrix2[i][j];
        }
    }
}

int main() {
    int rows = 3;
    int columns = 3;

    // Two matrices to be added
    int matrix1[3][3] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };
    int matrix2[3][3] = {
        {9, 8, 7},
        {6, 5, 4},
        {3, 2, 1}
    };

    // Matrix to store the result
    int result[3][3];

    // Perform matrix addition
    matrixAddition(rows, columns, matrix1, matrix2, result);

    // Print the original matrices
    printf("Matrix 1:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            printf("%d ", matrix1[i][j]);
        }
        printf("\n");
    }

    printf("\nMatrix 2:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            printf("%d ", matrix2[i][j]);
        }
        printf("\n");
    }

    // Print the result of matrix addition
    printf("\nMatrix Addition Result:\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            printf("%d ", result[i][j]);
        }
        printf("\n");
    }

    return 0;
}
Output:

Matrix 1:
1 2 3
4 5 6
7 8 9

Matrix 2:
9 8 7
6 5 4
3 2 1

Matrix Addition Result:
10 10 10
10 10 10
10 10 10
Explanation:
  • In the sample code, have two 3x3 matrices matrix1 and matrix2.
  • Also have a matrix result to store the result of the addition.
  • The function matrixAddition is used to perform the matrix addition, taking the number of rows, columns, two matrices, and the result matrix as parameters.
  • Using nested loops, iterate over each element of the matrices and calculate the sum, which is stored in the corresponding element of the result matrix.
  • The original matrices and the result of the matrix addition are printed using printf statements.

What operation combines two matrices in C?


Addition

What is the result of adding two matrices of the same dimensions?


Sum

In matrix addition, what must be true about the dimensions of the matrices being added?


Equal